package com.group4.Servlets;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.group4.DAO.UserDAO;
import com.group4.DB.User;

public class UpdatePasswordServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = -1350260752454599451L;

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String email = request.getParameter("email");
		String activationKey = request.getParameter("key");
		String password = request.getParameter("password");
		UserDAO user = User.getUser(email, activationKey);
		PrintWriter out = response.getWriter();
		JsonObject jsonObject = new JsonObject();
		if (user != null && user.getID() != -1) {
			
			user.setPassword(password);
			User.updateUser(user);
			Gson gson = new Gson();
            String json = gson.toJson(user);
            out.print(json);
			out.flush();

		} else {
			
			jsonObject.addProperty("error", "There is no such user");
			out.print(jsonObject);
			out.flush();
		}
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String email = request.getParameter("email");
		String activationKey = request.getParameter("key");
		String password = request.getParameter("password");
		UserDAO user = User.getUser(email, activationKey);
		PrintWriter out = response.getWriter();
		JsonObject jsonObject = new JsonObject();
		if (user != null && user.getID() != -1) {
			
			user.setPassword(password);
			User.updateUser(user);
			Gson gson = new Gson();
            String json = gson.toJson(user);
            out.print(json);
			out.flush();

		} else {
			
			jsonObject.addProperty("error", "There is no such user");
			out.print(jsonObject);
			out.flush();
		}
	}
}
